package com.huabo.push.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 通道管理
 * Created by Jackie Liu on 2017/7/12.
 */
public final class ChannelManager {

    private static final ConcurrentHashMap<String, CopyOnWriteArrayList<ChannelHandlerContext>> contextMap = new ConcurrentHashMap<String, CopyOnWriteArrayList<ChannelHandlerContext>>();

    public static void addChannel(String clientId, ChannelHandlerContext ctx) {
        CopyOnWriteArrayList<ChannelHandlerContext> list = contextMap.get(clientId);
        if (list == null) {
            list = new CopyOnWriteArrayList<ChannelHandlerContext>();
            CopyOnWriteArrayList<ChannelHandlerContext> result = contextMap.putIfAbsent(clientId, list);
            if (result != null) {
                list = result;
            }
        }
        list.add(ctx);
    }

    public static void remove(String clientId, ChannelHandlerContext ctx) {
        //Attribute<String> attr = ctx.channel().attr(AttributeKey.<String>valueOf("clientId"));
        //String clientId = attr.get();
        CopyOnWriteArrayList<ChannelHandlerContext> list = contextMap.get(clientId);
        if (list == null) {
            return;
        }
        list.remove(ctx);
    }

    public static boolean send(String clientId, String message) {
        CopyOnWriteArrayList<ChannelHandlerContext> list = contextMap.get(clientId);
        if (list == null || list.isEmpty()) {
            return false;
        }
        for (ChannelHandlerContext ctx : list) {
            if (ctx.channel().isActive()) {
                ctx.writeAndFlush(new TextWebSocketFrame(message));
            }
        }
        return true;
    }
}
